package com.mk.api.file;

import com.mk.base.exception.ApplicationException;
import com.mk.base.exception.StatusCode;
import com.mk.base.model.response.Rsp;
import com.mk.common.*;
import com.mk.common.office.Office2PDFUtil;
import com.mk.model.entity.*;
import com.mk.model.request.FileInfoRequest;
import com.mk.model.request.PacRequest;
import com.mk.service.IFileInfoService;
import com.mk.service.IPacService;
import com.mk.service.ITagService;
import com.mk.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yq
 * @Description:
 * @Date: Created in 3:38 PM 3/16/18
 */
@RestController
@RequestMapping("/file")
public class FileApi {

    @Autowired
    private IFileInfoService fileInfoService;
    @Autowired
    private IUserService userService;
    @Autowired
    private IPacService pacService;
    @Autowired
    private ITagService tagService;

    @Value("${location.fileupload.path}")
    private String FILE_UPLOAD_PATH;
    @Value("${location.imageupload.path}")
    private String IMAGE_UPLOAD_PATH;
    @Value("${openoffice.path}")
    private String openOfficePath;
    @Value("${pdf2htmlex.path}")
    private String pdf2htmlEXPath;

    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public Rsp uploadFile(@ModelAttribute("request")FileInfoRequest request){
        try{
            if(fileInfoService.saveFile(request))
                return Rsp.SUCCESS("上传文件成功");
            else
                return Rsp.ERROR("上传文件失败");
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(value = "/import/ready",method = RequestMethod.GET)
    public Rsp importReady(){
        try{
            UploadAll uploadAll = new UploadAll();
            List<DirPac> dirPacs = new ArrayList<>();
            File importPath = new File(FileConfig.ALL_IMPORT_PATH);
            File[] dirs = importPath.listFiles();
            if(dirs != null && dirs.length > 0){
                uploadAll.setNum(dirs.length);
                for (int i = 0; i < dirs.length; i++) {
                    String pacPath = FileConfig.ALL_IMPORT_PATH + dirs[i].getName() + "\\";
                    DirPac dirPac = new DirPac();
                    dirPac.setName(dirs[i].getName());
                    String [] pacs = new File(pacPath).list();
                    dirPac.setNum(pacs.length);
                    dirPac.setNames(pacs);
                    dirPacs.add(dirPac);
                }
                uploadAll.setPacs(dirPacs);
            }
            return Rsp.SUCCESS(uploadAll);
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    /**
     * 批量导入
     * @param userId
     * @return
     */
    @RequestMapping(value = "/import/all",method = RequestMethod.GET)
    public Rsp importAllPaces(@RequestParam("userId") Long userId){
        try{
            File importDir = new File(FileConfig.ALL_IMPORT_PATH);
            File[] dirs = importDir.listFiles();
            if(dirs != null && dirs.length > 0){
                for (int i = 0; i < dirs.length; i++) {
                    if(dirs[i].isDirectory()){
                        String pacPath = FileConfig.ALL_IMPORT_PATH + dirs[i].getName() + "\\";
                        String xmlPath = pacPath + FileConfig.DIR_XML_NODES.xmlName;
                        Tag tag = XmlHelper.parseXmlToTag(xmlPath);
                        Long nowDirId = tag.getPacId();
                        //创建资料包
                        PacRequest pacRequest  = new PacRequest();
                        pacRequest.setTitle(tag.getTitle());
                        pacRequest.setUserId(userId);
                        pacRequest.setDirId(nowDirId);
                        Pac pac = pacService.saveOnlyOne(pacRequest);
                        if(pac != null){
                            //创建资料包详情
                            File avator = new File(pacPath + tag.getAvator());
                            String url = FileUploadUtil.uploadFile(FileUtils.fileToMultipartFile(avator),IMAGE_UPLOAD_PATH);
                            tag.setAvator(url);//图片地址
                            tag.setPacId(pac.getId());
                            if(tagService.saveOnlyTag(tag)){
                                File pacFile = new File(pacPath);
                                //上传所有文件
                                File[] allPacFiles = pacFile.listFiles();
                                if(allPacFiles != null && allPacFiles.length > 0){
                                    for (int i1 = 0; i1 < allPacFiles.length; i1++) {
                                        File tf = allPacFiles[i];
                                        if(tf.isFile() && !tf.getName().equals(FileConfig.DIR_XML_NODES.avator)
                                                && !tf.getName().equals(FileConfig.DIR_XML_NODES.xmlName)){
                                            FileInfoRequest fileInfo = new FileInfoRequest();
                                            String turl = FileUploadUtil.copyOneFile(tf,FILE_UPLOAD_PATH);
                                            fileInfo.setName(tf.getName());
                                            fileInfo.setPname(turl);
                                            fileInfo.setSize(new Long(tf.length()).intValue() / 1024);
                                            fileInfo.setDirId(nowDirId);
                                            fileInfo.setPacId(pac.getId());
                                            if(fileInfoService.saveOnlyOne(fileInfo)){
                                                continue;
                                            }else{
                                                throw new ApplicationException(StatusCode.CONFLICT.getCode(),"上传文件出错了");
                                            }
                                        }
                                    }
                                }else
                                    throw new ApplicationException(StatusCode.CONFLICT.getCode(),"资料包:" + pac.getTitle() + "下没有文件");
                            }else
                                throw new ApplicationException(StatusCode.CONFLICT.getCode(),"创建资源包详情出错了");
                        }else
                            throw new ApplicationException(StatusCode.CONFLICT.getCode(),"创建资源包失败");
                    }
                }
                //删除import文件夹下的所有文件夹及文件
                FileUtils.deleteFolder(importDir.getPath());
                return Rsp.SUCCESS("批量上传成功");
            }else
                return Rsp.ERROR("批量上传的文件不可为空");
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    @RequestMapping(value = "/download",method = RequestMethod.GET)
    public Rsp downloadFile(@RequestParam("fileId") Long fileId){
        try{
            FileInfo fileInfo = fileInfoService.get(fileId);
            if(fileInfo != null){
                String fileName = fileInfo.getPname();
                File file = new File(FILE_UPLOAD_PATH + fileName);
                if(file.exists()){
                    return Rsp.SUCCESS(fileName);
                }
            }
            return Rsp.ERROR("您要下载的文件不存在");
        }catch (Exception e){
            return Rsp.ERROR(e.getMessage());
        }
    }

    /**
     * 预览
     */
    @RequestMapping(value = "/view",method = RequestMethod.GET)
    public Rsp showFile(@RequestParam("fileId") Long fileId){
        FileInfo fileInfo = fileInfoService.get(fileId);
        if(fileInfo == null)
            return Rsp.ERROR("预览的该文件不存在");
        String fileName = fileInfo.getPname();
        //该文件所在位置
        String filePath = FILE_UPLOAD_PATH + fileName;
        File sFile = new File(filePath);
        if(!sFile.exists())
            return Rsp.ERROR("转换的文件不存在");
        //转换后的pdf文件存放位置
        String pdfPath = FILE_UPLOAD_PATH + "pdf/";
        //如果是照片等直接可以预览
        if(FileUtils.isOther(fileName)) {
            return Rsp.SUCCESS(fileName);
        }
        if(!FileUtils.isOffice(fileName)){
            return Rsp.ERROR("该文件不支持预览");
        }
        File pdfFile = new File(pdfPath + fileName);
        if(pdfFile.exists())
            return Rsp.SUCCESS("pdf/" + fileName);
        int res = Office2PDFUtil.office2PDF(filePath,pdfPath + fileName,openOfficePath);
        if(res == 0)
            return Rsp.SUCCESS("pdf/" + fileName);
        else if(res == 1)
            return Rsp.ERROR("转pdf文件失败");
        else
            return Rsp.ERROR("转换的文件不存在");
    }
}